window.addEventListener("load", function () {
  var that;
  var flag = 3;
  class Tab {
    constructor(id) {
      that = this;
      this.mign = document.querySelector(id);
      this.ul = this.mign.querySelector("ul");
      console.log(this.ul);
      this.add = this.mign.querySelector(".tabadd");
      this.fseition = this.mign.querySelector(".tabscon");

      this.init();
    }
    // 调用获取的元素
    dy() {
      this.sections = this.mign.querySelectorAll("section");
      this.lis = this.mign.querySelectorAll("li");
      this.dels = this.ul.querySelectorAll(".iconfont");
      this.span = this.ul.querySelectorAll("li span:nth-child(1)");
      console.log(this.span);
      // this.int=this.span.querySelector('input')
      // console.log(this.int);
    }
    // 初始化
    init() {
      this.dy();
      for (var i = 0; i < this.lis.length; i++) {
        this.lis[i].index = i;
        this.lis[i].onclick = this.qh;
        that.dels[i].onclick = this.sc;
        this.span[i].ondblclick = this.xg;
        this.sections[i].ondblclick = this.xg;
      }
      this.add.onclick = this.tj;
    }
    // 1.切换
    qh() {
      that.clear();
      this.className = "liactive";
      that.sections[this.index].className = "conactive";
    }
    // 清除类名
    clear() {
      for (var i = 0; i < this.lis.length; i++) {
        this.lis[i].className = "";
        that.sections[i].className = "";
      }
    }
    // 2.添加
    tj() {
      // 1.创建li和section
      that.clear();
      flag++;
      var li = `<li class="liactive"><span>测试${flag}</span><span class="iconfont icon-guanbi"></span></li>`;
      var section = ` <section class="conactive">测试${flag}</section>`;
      // 2.把他们添加到对应的元素里面
      that.ul.insertAdjacentHTML("beforeend", li);
      that.fseition.insertAdjacentHTML("beforeend", section);
      that.init();
    }

    // 3.删除
    sc(e) {
      var index = this.parentNode.index;
      e //阻止冒泡[DOM推荐标准(ie678不兼容)]
        //ie678用cancelBubble = true
        //兼容处理快捷键jr-zzmp/jr-stopPropagation

        .stopPropagation();
      // this.parentNode.remove( );
      that.ul.removeChild(this.parentNode);
      // this.parentNodes[index-1].click()
      that.sections[index].remove();
      that.init();
      if (document.querySelector(".liactive")) return;
      index--;
      if(index<0){
        index=0
        // that.lis[index].click();
      }
      that.lis[index]&&that.lis[index].click()
     

      
    }
    // 4.修改
    xg() {
      var str = this.innerHTML;
      console.log("111");
      this.innerHTML = '<input type="text"/>';
      this.children[0].value = str;
      this.children[0].select();

      this.children[0].onblur = function () {
        // this.parentNode.innerHTML = this.value;
        this.parentNode.innerHTML = this.value;
      };
      this.children[0].onkeyup = function (e) {
        if (e.key === "Enter") this.blur();
      };
    }
  }
  new Tab("#tab");
  
});
